package com.ibm.sample.library.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.ibm.sample.library.dao.IGenericDao;

@SuppressWarnings("unchecked")
public class GenericDao<T> implements IGenericDao<T>
{
    @Autowired
    protected SessionFactory sessionFactory;

    protected Class<T> type;

    protected void setType(Class<T> type)
    {
        this.type = type;
    }

    @Override
    public T getById(long id)
    {
        return (T) getSession().get(type, id);
    }

    @Override
    public List<T> findAll()
    {
        return getSession().createCriteria(type).list();
    }

    @Override
    public Long save(T entity)
    {
        return (Long) getSession().save(entity);
    }

    @Override
    public void update(T entity)
    {
        getSession().merge(entity);
    }

    @Override
    public void delete(T entity)
    {
        getSession().delete(entity);
    }

    @Override
    public void deleteById(long id)
    {
        delete(getById(id));
    }

    protected Session getSession()
    {
        return sessionFactory.getCurrentSession();
    }
}
